package com.jiang.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


@WebServlet(name="DeptServlet",urlPatterns="/deptServlet/*")
public class DeptServlet extends HttpServlet {

	private static final long serialVersionUID = 4421526356843711590L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		// 这里主要是靠路径来区分调用的业务方法
		String uri = request.getRequestURI();
		String methodName = uri.substring(uri.lastIndexOf("/") + 1);
		try {
			Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
					HttpServletResponse.class);
			// 直接调用其方法，返回其结果
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * @读取部门XML数据
	 * @param request
	 * @param response
	 */
	public void  loadDepts(HttpServletRequest request, HttpServletResponse response){
		
		Document document = DocumentHelper.createDocument();
		Element rootEle = document.addElement("depts");
		for(int i=0;i<10;i++){
			Element deptEle = rootEle.addElement("dept");
			Element deptNoEle = deptEle.addElement("deptno");
			deptNoEle.setText(100+i+"00");
			Element dNameEle = deptEle.addElement("dname");
			dNameEle.setText("研发部"+i);
			Element dLoc = deptEle.addElement("loc");
			dLoc.setText("广州市城市街道"+i+"号");
		}
		OutputFormat format = OutputFormat.createCompactFormat();
		format.setEncoding("UTF-8");
		// 结果输出到页面
		try {
			XMLWriter writer = new XMLWriter(response.getWriter(), format);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
